<?php

namespace App\Service\WeChat;


use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;
use function Ramsey\Uuid\v1;

class MiniWx
{
    // 小程序接口
    protected $appid;
    protected $AppSecret;

    // 初始化操作
    public function __construct()
    {
        // 艺库小程序
        $this->appid     = 'wx519c562524bb167f';
        $this->AppSecret = '1e9ff8308564ca2aa9a2a29b5b10a4ca';

    }

    // 获取code


    // 获取用户信息（只是返回加密的一些相关信息）
    public function getUserByMini($access_token, $openid, $signature)
    {
        $_url = 'https://api.weixin.qq.com/wxa/business/getuserencryptkey?access_token='.$access_token.'&signature='.$signature.'&openid='.$openid.'&sig_method=hmac_sha256';
        //$params = ['appid' => $appid, 'secret' => $secret,  'grant_type' => 'client_credential'];
        //$_url   = 'https://api.weixin.qq.com/sns/oauth2/access_token'; //获取access_token和openid的链接
        //$res    = $this->curl($_url, $params);

        $res  = $this->curl($_url);
        $data = json_decode($res, true);

        return $data;
    }

    // 获取用户信息
    public function getPhoneByMini($access_token, $openid, $code)
    {
        $_url   = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token='.$access_token;
        $params = ['code' => $code, 'openid' => $openid,];
        $res    = $this->curl2($_url, $params);
        $data   = json_decode($res['result'], true);

        return $data;
    }

    // 获取openid
    public function _getOpenid($access_token, $code)
    {
        //$_url = 'https://api.weixin.qq.com/wxa/getpluginopenpid?access_token='.$access_token.'&code='.$code;
        $params = ['access_token' => $access_token, 'code' => $code,];
        $_url   = 'https://api.weixin.qq.com/wxa/getpluginopenpid'; //获取access_token和openid的链接

        $params = ['code' => $code,];
        $_url   = 'https://api.weixin.qq.com/wxa/getpluginopenpid?access_token='.$access_token; //获取access_token和openid的链接
        //$res    = $this->curl($_url, $params);

        $res = $this->curl2($_url, $params);

        var_dump($res);
        $data    = json_decode($res, true);
        $errcode = $data['errcode'];
        $errmsg  = $data['errmsg'];
        $openpid = $data['openpid'] ?? '';

        return $data;
    }

    // 获取
    public function getAccessToken()
    {
        $appid  = $this->appid; //appid
        $secret = $this->AppSecret;
        $_key   = $appid.'_getAccessToken';
        $_token = Cache::get($_key);

        if(empty($_token)){
            //获取access_token
            $_url = 'https://api.weixin.qq.com/cgi-bin/token?appid='.$appid.'&secret='.$secret.'&grant_type=client_credential';
            //$params = ['appid' => $appid, 'secret' => $secret,  'grant_type' => 'client_credential'];
            //$_url   = 'https://api.weixin.qq.com/sns/oauth2/access_token'; //获取access_token和openid的链接
            //$res    = $this->curl($_url, $params);

            $res    = $this->curl($_url);
            $data   = json_decode($res, true);
            $expire = $data['expires_in'];
            $_token = $data['access_token'];

            Cache::put($_key, $_token, 7000);
        }

        return $_token;
    }

    // 执行请求
    protected function curl($_url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_HTTP09_ALLOWED, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        $res = curl_exec($ch);

        curl_close($ch);

        return $res;
    }


    // 获取个人信息:小程序登录
    public function getOpenidByMini($code)
    {
        $appid  = $this->appid; //appid
        $secret = $this->AppSecret;
        $url    = "https://api.weixin.qq.com/sns/jscode2session?appid=$appid&secret=$secret&js_code=$code&grant_type=authorization_code";
        $res    = $this->curl($url);
        //var_dump($url);
        //var_dump($res);
        //$logger = new LogFile();
        //$logger->write('Request | 微信小程序请求openID返回 |' . var_export($res, 1), 'info');

        $data = json_decode($res, true);
        //$openid  = $data['openid'];
        //$session = $data['session_key'];

        return $data;
    }


    // 执行请求
    protected function curl2($url, $params = [], $expire = 0, $extend = array())
    {
        if(empty($url)){
            return array('code' => '100');
        }

        $_curl   = curl_init();
        $_header = array('Accept-Language: zh-CN', 'Connection: Keep-Alive', 'Cache-Control: no-cache',);
        // 只要第二个参数传了值之后，就是POST的
        if(!empty($params)){
            curl_setopt($_curl, CURLOPT_POSTFIELDS, ($params));
            curl_setopt($_curl, CURLOPT_POST, true);
        }
        curl_setopt($_curl, CURLOPT_HTTP09_ALLOWED, true);

        curl_setopt($_curl, CURLOPT_URL, $url);
        curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
        curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);
        if($expire > 0){
            curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
            curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
        }

        // 额外的配置
        if(!empty($extend)){
            curl_setopt_array($_curl, $extend);
        }

        // 执行结果 获取
        $result['result'] = curl_exec($_curl);
        Log::info('Request | 微信小程序请求openID返回 |'.$result['result']);

        $result['code'] = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
        $result['info'] = curl_getinfo($_curl);
        if($result['result'] === false){
            $result['result'] = curl_error($_curl);
            $result['code']   = -curl_errno($_curl);
        }

        curl_close($_curl);

        return $result;
    }


}


